#!/bin/bash

##################################
source ~/scriptbelt/bashutilities.sh
##################################

inputpath="$1"
relativegzipfile="$1"
remoteconvert=false

for iarg in $*; do
    option=`echo "$iarg" | cut -d"=" -f1`
    if [ "$option" == "-h"  ]; then
	echo "available options are:"
	echo "--remote"
	echo "--targetcrosssection"
	echo "--file"
	exit
    fi

    if [ "$option" == "--remote"  ]; then
	remoteconvert=true
    fi

    if [ "$option" == "--file"  ]; then
	relativegzipfile=`echo "$iarg" | cut -d"=" -f2`
    fi

    if [ "$option" == "--forcerelativepath"  ]; then
	relativegzipfile="${inputpath##*/}"
	##### THIS WILL MAKE ALL PATHS RELATIVE ########
    fi
    
    if [ "$option" == "--targetcrosssection"  ]; then
	targetcrosssection=true
	targetsigma=`echo "$iarg" | cut -d"=" -f2`
	echo -e "events will be reweighted to same weight and integrated weight equal to "$RED$targetsigma" pb"$COL_RESET
    fi

done 

basefilename=`echo "$relativegzipfile" | rev | cut -c 4- | rev`
echo $basefilename 
####gzfile=`echo "$basefilename"".gz"`
gzfile="$basefilename"".gz"
####lhcofile=`echo "$basefilename"`
lhcofile="$basefilename"
####lhefile=`echo $basefilename".lhe"`
lhefile="$basefilename"".lhe"
echo "$gzfile"

if [ "$remoteconvert" = true ]; then
    options=""
    echo -e $RED"Converting to ROOT on the remote machine"$COL_RESET
    scp "$gzfile" rfrances@hepcms-in1.umd.edu:~/landing/
    
    if [ "$targetcrosssection" = true ]; then
	options=$options" --targetcrosssection="$targetsigma
    fi
    oneliner="cd landing;ls -l; lhco2root.sh ""$gzfile"$options
    echo -e $RED"$oneliner"$COL_RESET
    ssh  rfrances@hepcms-in1.umd.edu "$oneliner"
    ssh  rfrances@hepcms-in1.umd.edu "cd landing;ls -l;"
    scp  rfrances@hepcms-in1.umd.edu:~/landing/"$lhefile""*.root" .
    ssh  rfrances@hepcms-in1.umd.edu "rm -v ~/landing/*"
    
else
    echo -e $RED"Converting to ROOT on the local machine"$COL_RESET
###action!####
lines=`gunzip -h | wc -l`
echo "gzip is "$lines

if [ $lines -gt 0 ]; then
    gunzip -c "$gzfile" > "$lhcofile"
else 
    gunzip "$gzfile"
fi

#relativelhcofile="${lhcofile##*/}"
echo "path to LHCO file ""$lhcofile"
lhco2lhe "$lhcofile"
echo -e "$lhefile"" has been created"

if [ "$targetcrosssection" = true ]; then
    lhetools targetcrosssection,"$targetsigma" "$lhefile"
    finallhefile="$lhefile""targetcrosssection,""$targetsigma"".lhe"
    echo -e $RED"$finallhefile"" has been created"$COL_RESET
else 
    finallhefile="$lhefile"
fi

 
    myExRootLHEFConverter "$finallhefile"   
fi




